//
//  XGMineConcernTableViewCell.swift
//  TodayNews
//
//  Created by monkey on 2020/2/4.
//  Copyright © 2020 itcast. All rights reserved.
//

import UIKit
import SwiftTheme
import Kingfisher

protocol XGMineConcernTableViewCellDelegate: AnyObject
{
    func concernUserDidSelected(_ concernUser: XGConcernUserModel) -> Void
}

// MARK: - XGMineConcernTableViewCell

class XGMineConcernTableViewCell: UITableViewCell,XGRegisterReusableViewProtocol
{
    /// 代理
    weak var delegate: XGMineConcernTableViewCellDelegate?
    
    /// 关注用户列表
     var concernUsers: [XGConcernUserModel]? {
        didSet {
            guard let concernUsers = concernUsers else {
                return
            }
            
            let count = concernUsers.count
            concernUserButton.isHidden = count != 1
            concernUsersCollectionView.isHidden = count <= 1
            
            if count == 1 {
                concernUserButton.setTitle(concernUsers[0].name, for: .normal)
                let url = concernUsers[0].icon
                if url != nil {
                    concernUserButton.kf.setImage(with: URL(string: url!), for: .normal, options: [.processor( DownsamplingImageProcessor(size: CGSize(width: 36, height: 36)))])
                }
            } else if count > 1 {
                concernUsersCollectionView.reloadData()
            }
        }
    }
    
    // MARK: 构造方法
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?)
    {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        selectionStyle = .none
        setUpUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 标题
    private lazy var titleLabel: UILabel = UILabel(text: "我的关注", textColor: UIColor.darkGray, fontSize: 17, textAlignment: .left)
    /// 关注用户
    private lazy var concernUserButton: UIButton = { [weak self] in
        let button = UIButton(type: .custom)
        button.theme_setTitleColor("colors.cell_title", forState: .normal)
        button.theme_backgroundColor = "colors.cell_background"
        button.layoutButtonWithEdgInsetStyle(.imageLeft, space: 10)
        button.addTarget(self, action: #selector(concernUserButtonAction), for: .touchUpInside)
        return button
    }()
    /// 箭头
    private lazy var arrowImageView: UIImageView = UIImageView(image: UIImage(named: "setting_rightarrow_8x14_"))
    /// 关注列表
    private lazy var concernUsersCollectionView: UICollectionView = { [weak self] in
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: XGConcernCollectionViewFlowLayout())
        collectionView.theme_backgroundColor = "colors.cell_background"
        collectionView.isPagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
        collectionView.dataSource = self
        collectionView.delegate = self
        collectionView.xg_registerCell(cellType: XGConcernCollectionViewCell.self)
        return collectionView
    }()
}

// MARK: 数据源和代理

extension XGMineConcernTableViewCell: UICollectionViewDataSource,UICollectionViewDelegate
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return concernUsers?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath)
        -> UICollectionViewCell
    {
        let cell = collectionView.xg_dequeueReusableCell(indexPath: indexPath) as XGConcernCollectionViewCell
        cell.concernUser = concernUsers?[indexPath.item]
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        guard let concernUsersModel = concernUsers?[indexPath.item] else {
            return
        }
        
        delegate?.concernUserDidSelected(concernUsersModel)
    }
}

// MARK: 私有扩展

private extension XGMineConcernTableViewCell
{
    /// 关注用户按钮事件
    @objc func concernUserButtonAction() -> Void
    {
        guard let concernUsersModel = concernUsers?.first else {
            return
        }
        
        delegate?.concernUserDidSelected(concernUsersModel)
    }
    
    /// 设置界面
    func setUpUI() -> Void
    {
        theme_backgroundColor = "colors.cell_background"
        titleLabel.theme_textColor = "colors.cell_title"
        
        let topView = UIView()
        topView.addSubview(titleLabel)
        topView.addSubview(arrowImageView)
        topView.addSubview(concernUserButton)
        contentView.addSubview(topView)
        contentView.addSubview(concernUsersCollectionView)
        
        titleLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(20)
            make.centerY.equalToSuperview()
        }
        
        arrowImageView.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-20)
            make.centerY.equalToSuperview()
        }
        
        concernUserButton.snp.makeConstraints { (make) in
            make.right.equalTo(arrowImageView.snp.left).offset(-10)
            make.centerY.equalToSuperview()
            make.height.equalToSuperview()
            make.width.equalTo(180)
        }
                
        topView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(44.0)
        }
        
        concernUsersCollectionView.snp.makeConstraints { (make) in
            make.top.equalTo(topView.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
    }
}

// MARK: - XGConcernCollectionViewFlowLayout

private class XGConcernCollectionViewFlowLayout: UICollectionViewFlowLayout
{
    override func prepare()
    {
        super.prepare()
        
        let itemWidth = max(collectionView!.bounds.height, 64)
        scrollDirection = .horizontal
        itemSize = CGSize(width: itemWidth, height: itemWidth)
        minimumLineSpacing = 0.0
        sectionInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
    }
}

// MARK: - XGConcernCollectionViewCell

private class XGConcernCollectionViewCell: UICollectionViewCell,XGRegisterReusableViewProtocol
{
    /// 关注用户数据模型
    var concernUser: XGConcernUserModel? {
        didSet {
            if let url = concernUser?.icon {
                userIconImageView.kf.setImage(with: URL(string: url))
            }
            
            userNameLabel.text = concernUser?.name
            verifyImageView.isHidden = concernUser?.is_verify != true
        }
    }
    
    override init(frame: CGRect)
    {
        super.init(frame: frame)
        
        setUpUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /// 设置界面
    private func setUpUI() -> Void
    {
        theme_backgroundColor = "colors.cell_background"
        userNameLabel.theme_textColor = "colors.cell_title"
        
        
        contentView.addSubview(userIconImageView)
        contentView.addSubview(userNameLabel)
        contentView.addSubview(verifyImageView)
        
        userIconImageView.snp.makeConstraints { (make) in
            make.top.centerX.equalToSuperview()
            make.size.equalTo(CGSize(width: 40, height: 40))
        }
        
        userNameLabel.snp.makeConstraints { (make) in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(userIconImageView.snp.bottom).offset(3)
        }
        
        verifyImageView.snp.makeConstraints { (make) in
            make.centerX.equalTo(userIconImageView.snp.right).offset(-5)
            make.centerY.equalTo(userIconImageView.snp.bottom).offset(-5)
        }
    }
    
    /// 头像
    private lazy var userIconImageView: UIImageView = UIImageView()
    /// 用户名
    private lazy var userNameLabel: UILabel = UILabel(text: "测试", textColor: UIColor.darkGray, fontSize: 10, textAlignment: .center)
    /// 认证标识
    private lazy var verifyImageView: UIImageView = UIImageView(image: UIImage(named: "all_v_avatar_18x18_"))
}
